package src

import (
	"net/http"
	"text/template"
	"time"
	"webssh/src/controller"
	"webssh/src/middleware"

	"github.com/gin-contrib/gzip"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func NewServer() *gin.Engine {
	server := gin.Default()
	server.SetTrustedProxies(nil)
	server.Use(gzip.Gzip(gzip.DefaultCompression))
	// auth
	server.Use(middleware.ParseUserToken())
	server.Use(gin.Recovery())

	// redister router
	registerWebHandler(server)
	registerWebsocketHandler(server)
	registerFilemanagerHandler(server)
	return server
}

// Register web Handler
func registerWebHandler(router *gin.Engine) {
	router.GET("static/index.html", func(c *gin.Context) {
		r := c.Request
		r.ParseForm()
		t, err := template.ParseFiles("static/index.html")
		if err != nil {
			http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
			return
		}
		t.Execute(c.Writer, "")
	})
}

// Register websocket Handler
func registerWebsocketHandler(router *gin.Engine) {
	router.GET("/webssh/term", func(c *gin.Context) {
		controller.TermWs(c, time.Duration(viper.GetInt64("websocket.timeout"))*time.Minute)
	})
	router.Any("/vncproxy/:port", func(c *gin.Context) {
		controller.ProxyVnc(c, time.Duration(viper.GetInt64("websocket.timeout"))*time.Minute)
	})
	router.GET("/webssh/term/check", func(c *gin.Context) {
		c.JSON(200, controller.CheckSSH(c))
	})
}

// Register filemanager Handler
func registerFilemanagerHandler(router *gin.Engine) {
	router.GET("/webssh/file/list", func(c *gin.Context) {
		c.JSON(200, controller.FileList(c))
	})
	router.GET("/webssh/file/create", func(c *gin.Context) {
		c.JSON(200, controller.CreateFile(c))
	})
	router.GET("/webssh/file/mkdir", func(c *gin.Context) {
		c.JSON(200, controller.Mkdir(c))
	})
	router.GET("/webssh/file/content", func(c *gin.Context) {
		c.JSON(200, controller.FileContent(c))
	})
	router.DELETE("/webssh/file", func(c *gin.Context) {
		c.JSON(200, controller.RemoveFile(c))
	})
	router.POST("/webssh/file/rename", func(c *gin.Context) {
		c.JSON(200, controller.Rename(c))
	})
	router.POST("/webssh/file/update", func(c *gin.Context) {
		c.JSON(200, controller.UpdateFile(c))
	})
	router.GET("/webssh/file/download", func(c *gin.Context) {
		controller.DownloadFile(c)
	})
	router.POST("/webssh/file/upload", func(c *gin.Context) {
		c.JSON(200, controller.UploadFile(c))
	})
	router.GET("/webssh/file/progress", func(c *gin.Context) {
		controller.UploadProgress(c)
	})
	// 大文件上传
	router.POST("/webssh/bigfile/upload", func(c *gin.Context) {
		c.JSON(200, controller.UploadBigFile(c))
	})
	router.POST("/webssh/bigfile/chunks", func(c *gin.Context) {
		c.JSON(200, controller.Chunks(c))
	})
}
